package pushlog

import (
	"errors"
	"net/smtp"
	"strings"

	"gitee.com/xuesongtao/collect/library"
	"github.com/gogf/gf/frame/g"
	jemail "github.com/jordan-wright/email"
)

type EmailPush struct {
	SmtpServer   string // smtp 服务器(host:prot)
	SendUserName string
	SendPassword string   // 授权码
	From         string   // 发件人
	To           []string // 收件人
	Cc           []string // 抄送人
}

func NewEmailPush() *EmailPush {
	obj := &EmailPush{SmtpServer: g.Cfg().GetString("email.smtp_server")}
	obj.SendUserName = library.DecFn(g.Cfg().GetString("email.send_username"))
	obj.SendPassword = library.DecFn(g.Cfg().GetString("email.send_password"))
	obj.From = library.DecFn(g.Cfg().GetString("email.from"))
	return obj
}

func (e *EmailPush) SetFrom(from string) *EmailPush {
	e.From = from
	return e
}

func (e *EmailPush) SetTo(to ...string) *EmailPush {
	if e.To == nil {
		e.To = make([]string, 0, 5)
	}
	e.To = append(e.To, to...)
	return e
}

func (e *EmailPush) SetCc(Cc string) *EmailPush {
	if e.Cc == nil {
		e.Cc = make([]string, 0, 5)
	}
	e.Cc = append(e.Cc, Cc)
	return e
}

func (e *EmailPush) Push(subject string, content string) error {
	defer e.reset()
	email := jemail.NewEmail()
	if e.From == "" {
		e.From = library.DecFn(g.Cfg().GetString("email.from"))
	}
	email.From = e.From
	email.To = e.To
	email.Cc = e.Cc
	if subject == "" {
		subject = ErrLogTitle
	}
	email.Subject = subject
	email.Text = []byte(content)
	serverHostLastIndex := strings.Index(e.SmtpServer, ":")
	if serverHostLastIndex < 0 {
		return errors.New("SmtpServer not have port")
	}
	serverHost := e.SmtpServer[0:serverHostLastIndex]
	if err := email.Send(e.SmtpServer, smtp.PlainAuth("", e.SendUserName, e.SendPassword, serverHost)); err != nil {
		return err
	}
	return nil
}

func (e *EmailPush) reset() {
	e.From = ""
	e.To = nil
	e.Cc = nil
}
